﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.SessionState;
using LosConn.BLL;
using System.Text;
using System.Data;

namespace LosConn.Web.Handler
{
    /// <summary>
    /// OrderHandler 的摘要说明
    /// </summary>
    public class OrderHandler : IHttpHandler, IReadOnlySessionState
    {

        private BLL.Los_Product bllProduct = new BLL.Los_Product();
        private BLL.Los_Type bllType = new BLL.Los_Type();
        private BLL.Los_Order bllOrder = new Los_Order();
        private BLL.Los_Retail bllRetail = new Los_Retail();
        private BLL.Los_Guest bllGuest = new Los_Guest();
        public void ProcessRequest(HttpContext context)
        {
            String strResult = String.Empty;
            switch (context.Request["fun"])
            {

                //case "f_0001": //获取类型
                //    strResult = GetTypeSelect();
                //    break;
                case "f_0001": //根据类型ID获取产品列表
                    strResult = GetProductByTypeID(context);
                    break;
                case "f_0002": //下订单
                    strResult = AddOrder(context);
                    break;
                case "f_0003": //下辅助品订单
                    strResult = AddSupplementsOrder(context);
                    break;
                case "f_0005": //财务扣款
                    strResult = PayOrder(context);
                    break;
                case "f_0006": //物流发货
                    strResult = FlowOrder(context);
                    break;
                default:
                    break;
            }

            context.Response.Write(strResult);
            context.Response.End();
        }

        #region 私有方法
        /// <summary>
        /// 获取类型
        /// </summary>
        private String GetTypeSelect()
        {
            StringBuilder sb = new StringBuilder(500);
            DataTable dt = bllType.GetList(" Type_Status=100 ").Tables[0];
            sb.Append("<select id=\"Type_ID\" class=\"input-medium\">");
            if (dt != null && dt.Rows.Count > 0)
            {
                foreach (DataRow dr in dt.Rows)
                {
                    sb.AppendFormat("<option value=\"{0}\">{1}</option>", dr["Type_ID"], dr["Type_Name"]);
                }
            }
            sb.Append("</select>");
            return sb.ToString();
        }

        /// <summary>
        /// 根据类型ID获取产品列表
        /// </summary>
        private String GetProductByTypeID(HttpContext context)
        {
            StringBuilder sb = new StringBuilder(2000);
            sb.Append("<table class=\"table table-bordered table-striped table-hover with-check\">");
            DataTable dt = bllProduct.GetList(String.Format(" Product_TypeID={0} and Product_Status=100 ", context.Request["Type_ID"])).Tables[0];
            sb.Append("<thead><tr><th></th><th>产品编码</th><th>产品名称</th><th>金额</th></tr></thead>");
            sb.Append("<tbody>");
            if (dt != null && dt.Rows.Count > 0)
            {
                foreach (DataRow dr in dt.Rows)
                {
                    sb.AppendFormat("<tr><td><input vid=\"type{0}\" value=\"{1}\" val1=\"{4}\" class=\"shopCheck\" type=\"checkbox\" /></td><td class=\"Product_Code\">{2}<input type=\"hidden\" class=\"Product_ID\" value=\"{1}\" /></td><td class=\"Product_Name\">{3}</td><td>{5}<input type=\"hidden\" class=\"Product_Money\" value=\"{5}\" /></td></tr>", context.Request["Type_ID"], dr["Product_ID"], dr["Product_Code"], dr["Product_Name"], context.Request["Type_Name"], dr["Product_Price"]);
                }
            }
            else
            {
                sb.Append("<tr><td colspan=\"3\">暂无数据...</td></tr>");
            }
            sb.Append("</tbody>");
            sb.Append("</table>");
            return sb.ToString();
        }

        /// <summary>
        /// 下订单
        /// </summary>
        /// <param name="context"></param>
        /// <returns></returns>
        private String AddOrder(HttpContext context)
        {
            String Order_GuestID = context.Request["Order_GuestID"].ToString(); //客户ID
            String Order_Remark = "";// context.Request["Order_Remark"].ToString(); //备注 先不管
            String OrderProduct_ProductID = context.Request["OrderProduct_ProductID"].ToString(); //产品ID
            String OrderProduct_Number = context.Request["OrderProduct_Number"].ToString();//产品数量
            String OrderProduct_Remark = "";// context.Request["OrderProduct_Remark"].ToString();//产品备注 先不管
            String OrderProduct_Money = context.Request["OrderProduct_Money"].ToString();//产品金额
            Int32 UserID = Convert.ToInt32(context.Session["UserID"]);
            String UserName = context.Session["UserName"].ToString();
            Int32 Retail_ID = Convert.ToInt32(context.Session["Retail_ID"]);
            String[] ProductID = OrderProduct_ProductID.Split(',');
            String[] Number = OrderProduct_Number.Split(',');
            String[] Money = OrderProduct_Money.Split(',');
            DateTime Time = DateTime.Now;
            Model.Los_OrderProduct orderProductModel = null;
            Decimal Order_Money = 0;
            for (Int32 i = 0; i < Money.Length; i++)
            {
                Order_Money += Convert.ToDecimal(Money[i]) * Convert.ToInt32(Number[i]);
            }
            Model.Los_Retail modelRetail = new Model.Los_Retail();
            modelRetail.Retail_Money = Order_Money;
            modelRetail.Retail_ID = Retail_ID;
            //if (!bllRetail.UpdatePrice(modelRetail))
            //{
            //    return "{" + WebClass.RESULT_CODE_ERROR + "," + WebClass.RESULT_INFO + "\"您的余额不足，请充值！\"}";
            //}
            Model.Los_Order orderModel = new Model.Los_Order();
            orderModel.Order_AddDate = Time;
            orderModel.Order_GuestID = Convert.ToInt32(Order_GuestID);
            orderModel.Order_Money = Order_Money;
            orderModel.Order_Remark = "";
            orderModel.Order_RetailID = Retail_ID;
            //orderModel.Order_Status = 500;
            orderModel.Order_Status = 800;
            orderModel.Order_UserID = UserID;
            orderModel.Order_UserName = UserName;
            Int32 Order_ID = bllOrder.AddOrder(orderModel);
            for (Int32 i = 0; i < ProductID.Length; i++)
            {
                orderProductModel = new Model.Los_OrderProduct();
                orderProductModel.OrderProduct_AddDate = Time;
                orderProductModel.OrderProduct_Money = Convert.ToDecimal(Money[i]) * Convert.ToInt32(Number[i]);
                orderProductModel.OrderProduct_Number = Convert.ToInt32(Number[i]);
                orderProductModel.OrderProduct_OrderID = Order_ID;
                orderProductModel.OrderProduct_ProductID = Convert.ToInt32(ProductID[i]);
                orderProductModel.OrderProduct_Remark = "";
                orderProductModel.OrderProduct_Status = 100;
                orderProductModel.OrderProduct_UserID = UserID;
                orderProductModel.OrderProduct_UserName = UserName;
                bllOrder.AddOrderProduct(orderProductModel);
            }
            Model.Los_Guest guestModel = new Model.Los_Guest();
            guestModel.Guest_ID = Convert.ToInt32(Order_GuestID);
            //guestModel.Guest_Stauts = 500;
            guestModel.Guest_Stauts = 800;
            bllGuest.UpdateGuestOrder(guestModel);
            String retMsg = bllRetail.CheckPrice(modelRetail);
            bllRetail.UpdatePrice(modelRetail, ref retMsg);
            if (retMsg != "1")
                return "{" + WebClass.RESULT_CODE_SUCCESS + "," + WebClass.RESULT_INFO + "\"" + WebClass.RESULT_SUCCESS_LAN + "\"}";
            else
                return "{" + WebClass.RESULT_CODE_SUCCESS + "," + WebClass.RESULT_INFO + "\"" + WebClass.RESULT_SUCCESS_LAN + "\",\"r_msg\":\"订单提交成功！您的账户余额不足，为保障您的订单正常，请及时联系财务人员充值，以免造成不便！\"}";
        }

        /// <summary>
        /// 下辅助品订单
        /// </summary>
        /// <param name="context"></param>
        /// <returns></returns>
        private String AddSupplementsOrder(HttpContext context)
        {
            //String Order_GuestID = context.Request["Order_GuestID"].ToString(); //客户ID
            String Order_Remark = "";// context.Request["Order_Remark"].ToString(); //备注 先不管
            String OrderProduct_ProductID = context.Request["OrderProduct_ProductID"].ToString(); //产品ID
            String OrderProduct_Number = context.Request["OrderProduct_Number"].ToString();//产品数量
            String OrderProduct_Remark = "";// context.Request["OrderProduct_Remark"].ToString();//产品备注 先不管
            String OrderProduct_Money = context.Request["OrderProduct_Money"].ToString();//产品金额
            Int32 UserID = Convert.ToInt32(context.Session["UserID"]);
            String UserName = context.Session["UserName"].ToString();
            Int32 Retail_ID = Convert.ToInt32(context.Session["Retail_ID"]);
            String[] ProductID = OrderProduct_ProductID.Split(',');
            String[] Number = OrderProduct_Number.Split(',');
            String[] Money = OrderProduct_Money.Split(',');
            DateTime Time = DateTime.Now;
            Model.Los_OrderProduct orderProductModel = null;
            Decimal Order_Money = 0;
            for (Int32 i = 0; i < Money.Length; i++)
            {
                Order_Money += Convert.ToDecimal(Money[i]) * Convert.ToInt32(Number[i]);
            }
            //Model.Los_Retail modelRetail = new Model.Los_Retail();
            //modelRetail.Retail_Money = Order_Money;
            //modelRetail.Retail_ID = Retail_ID;
            //if (!bllRetail.UpdatePrice(modelRetail))
            //{
            //    return "{" + WebClass.RESULT_CODE_ERROR + "," + WebClass.RESULT_INFO + "\"您的余额不足，请充值！\"}";
            //}
            Model.Los_Order orderModel = new Model.Los_Order();
            orderModel.Order_AddDate = Time;
            orderModel.Order_GuestID = 0;
            orderModel.Order_Money = Order_Money;
            orderModel.Order_Remark = "";
            orderModel.Order_RetailID = Retail_ID;
            //orderModel.Order_Status = 500;
            orderModel.Order_Status = 800;
            orderModel.Order_UserID = UserID;
            orderModel.Order_UserName = UserName;
            Int32 Order_ID = bllOrder.AddOrder(orderModel);
            for (Int32 i = 0; i < ProductID.Length; i++)
            {
                orderProductModel = new Model.Los_OrderProduct();
                orderProductModel.OrderProduct_AddDate = Time;
                orderProductModel.OrderProduct_Money = Convert.ToDecimal(Money[i]) * Convert.ToInt32(Number[i]);
                orderProductModel.OrderProduct_Number = Convert.ToInt32(Number[i]);
                orderProductModel.OrderProduct_OrderID = Order_ID;
                orderProductModel.OrderProduct_ProductID = Convert.ToInt32(ProductID[i]);
                orderProductModel.OrderProduct_Remark = "";
                orderProductModel.OrderProduct_Status = 100;
                orderProductModel.OrderProduct_UserID = UserID;
                orderProductModel.OrderProduct_UserName = UserName;
                bllOrder.AddOrderProduct(orderProductModel);
            }
            //Model.Los_Guest guestModel = new Model.Los_Guest();
            //guestModel.Guest_ID = Convert.ToInt32(Order_GuestID);
            //guestModel.Guest_Stauts = 500;
            //bllGuest.UpdateGuestOrder(guestModel);
            //return "{" + WebClass.RESULT_CODE_SUCCESS + "," + WebClass.RESULT_INFO + "\"" + WebClass.RESULT_SUCCESS_LAN + "\"}";
            Model.Los_Retail modelRetail = new Model.Los_Retail();
            modelRetail.Retail_Money = Order_Money;
            modelRetail.Retail_ID = Retail_ID;
            String retMsg = bllRetail.CheckPrice(modelRetail);
            bllRetail.UpdatePrice(modelRetail, ref retMsg);
            if (retMsg != "1")
                return "{" + WebClass.RESULT_CODE_SUCCESS + "," + WebClass.RESULT_INFO + "\"" + WebClass.RESULT_SUCCESS_LAN + "\"}";
            else
                return "{" + WebClass.RESULT_CODE_SUCCESS + "," + WebClass.RESULT_INFO + "\"" + WebClass.RESULT_SUCCESS_LAN + "\",\"r_msg\":\"订单提交成功！您的账户余额不足，为保障您的订单正常，请及时联系财务人员充值，以免造成不便！\"}";
        }

        /// <summary>
        /// 财务扣款
        /// </summary>
        /// <param name="context"></param>
        /// <returns></returns>
        private String PayOrder(HttpContext context)
        {
            Model.Los_Retail modelRetail = new Model.Los_Retail();
            BLL.Los_Order bllOrder = new Los_Order();
            Int32 Order_ID = Convert.ToInt32(context.Request.Form["id"]);
            String retMsg = String.Empty;
            Model.Los_Order modelOrder = bllOrder.GetModel(Order_ID);
            modelRetail.Retail_Money = Convert.ToDecimal(modelOrder.Order_Money);
            modelRetail.Retail_ID = Convert.ToInt32(modelOrder.Order_RetailID);
            bllRetail.UpdatePrice(modelRetail, ref retMsg);
            //{
            //    return "{" + WebClass.RESULT_CODE_ERROR + "," + WebClass.RESULT_INFO + "\"该用户余额不足，请充值！\"}";
            //}
            //else
            //{
            if (!modelOrder.Order_GuestID.ToString().Equals("0"))
            {
                Model.Los_Guest modelGuest = new Model.Los_Guest();
                modelGuest.Guest_Stauts = 800;
                modelGuest.Guest_ID = Convert.ToInt32(modelOrder.Order_GuestID);
                bllGuest.UpdateGuestOrder(modelGuest);
            }
            modelOrder.Order_Status = 800;
            bllOrder.UpdateOrderPay(modelOrder);
            if (retMsg.Equals("1"))
                return "{" + WebClass.RESULT_CODE_SUCCESS + "," + WebClass.RESULT_INFO + "\"" + WebClass.RESULT_SUCCESS_LAN_PAYOFF + "\"}";
            else
                return "{" + WebClass.RESULT_CODE_SUCCESS + "," + WebClass.RESULT_INFO + "\"" + WebClass.RESULT_SUCCESS_LAN + "\"}";
            //}
        }

        /// <summary>
        /// 物流发货
        /// </summary>
        /// <param name="context"></param>
        /// <returns></returns>
        private String FlowOrder(HttpContext context)
        {
            Model.Los_Retail modelRetail = new Model.Los_Retail();
            BLL.Los_Order bllOrder = new Los_Order();
            Int32 Order_ID = Convert.ToInt32(context.Request.Form["id"]);
            String retMsg = String.Empty;
            Model.Los_Order modelOrder = bllOrder.GetModel(Order_ID);
            modelRetail.Retail_Money = Convert.ToDecimal(modelOrder.Order_Money);
            modelRetail.Retail_ID = Convert.ToInt32(modelOrder.Order_RetailID);
            //bllRetail.UpdatePrice(modelRetail, ref retMsg);
            //{
            //    return "{" + WebClass.RESULT_CODE_ERROR + "," + WebClass.RESULT_INFO + "\"该用户余额不足，请充值！\"}";
            //}
            //else
            //{
            if (!modelOrder.Order_GuestID.ToString().Equals("0"))
            {
                Model.Los_Guest modelGuest = new Model.Los_Guest();
                modelGuest.Guest_Stauts = 700;
                modelGuest.Guest_ID = Convert.ToInt32(modelOrder.Order_GuestID);
                bllGuest.UpdateGuestOrder(modelGuest);
            }
            modelOrder.Order_Status = 700;
            bllOrder.UpdateOrderPay(modelOrder);
            return "{" + WebClass.RESULT_CODE_SUCCESS + "," + WebClass.RESULT_INFO + "\"" + WebClass.RESULT_SUCCESS_LAN + "\"}";
            //}
        }
        #endregion

        public bool IsReusable
        {
            get
            {
                return false;
            }
        }
    }
}